﻿#define _CRT_SECURE_NO_WARNINGS 1

//CSDN C++第十六篇博客
//C++的心脏：深入理解内存管理中的 new 和 delete

#include<iostream>
#include<stdlib.h>
using namespace std;

//C语言中的内存管理
//题目
//int globalVar = 1;
//static int staticGlobalVar = 1;
//void Test()
//{
//	static int staticVar = 1;
//	int localVar = 1;
//	int num1[10] = { 1, 2, 3, 4 };
//	char char2[] = "abcd";
//	const char* pChar3 = "abcd";
//	int* ptr1 = (int*)malloc(sizeof(int) * 4); int* ptr2 = (int*)calloc(4, sizeof(int)); int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4); free(ptr1);
//	free(ptr3);
//}
////1. 选择题：
////选项 : A.栈  B.堆  C.数据段(静态区)  D.代码段(常量区)    globalVar在哪里？____   staticGlobalVar在哪里？____    staticVar在哪里？____   localVar在哪里？____
////num1 在哪里？____
////
////char2在哪里？____ * char2在哪里？___    pChar3在哪里？____ * pChar3在哪里？____    ptr1在哪里？____ * ptr1在哪里？____
////2. 填空题：
//sizeof(num1) = ____; 
//sizeof(char2) = ____;     
//strlen(char2) = ____;   
//sizeof(pChar3) = ____;    
//strlen(pChar3) = ____;    
//sizeof(ptr1) = ____;

//3.1 new/delete
//代码一
int main()
{
	int* p1 = new int;       // 分配内存给一个整数
	int* p2 = new int[10];   // 分配内存给一个包含 10 个整数的数组

	delete p1;               // 释放 p1 指向的内存
	delete[] p2;             // 释放 p2 指向的整个数组的内存

	return 0;
}
//代码二
int main()
{
	int* p3 = new int(10);
	int* p4 = new int[10]{1,2,3,4};

	delete p3;
	delete[] p4;

	return 0;
}

//代码三
struct ListNode
{
	ListNode(int val)
		:_next(nullptr)
		,_prev(nullptr)
		,_val(val)
	{}


	ListNode* _next;
	ListNode* _prev;
	int _val;
};

struct ListNode* CreateListNode(int val)
{
	struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return 0;
	}

	newnode->_prev = NULL;
	newnode->_next = NULL;
	newnode->_val = val;

	return newnode;
}

int main()
{
	ListNode* node1 = new ListNode(1);
	ListNode* node2 = new ListNode(2);
	ListNode* node3 = new ListNode(3);

	delete node1;
	delete node2;
	delete node3;

	return 0;
}


//operator new 和 operator delete
int main()
{
	int* p1 = (int*)operator new(4 * 10);
	char* p = new char[100];
	delete p;
	return 0;
}



